<?php defined('SYSPATH') OR die('No direct access allowed.');

class Site_Auth_Controller extends Web_Controller {

  public function __construct() {
    parent::__construct();
  }

  public function login() {
    $this->user AND url::redirect(url::base(FALSE).'site_auth/profile');
    $this->template->content = new View('auth/login');
    $this->template->title = 'Авторизация пользователя';
    $errors = array();
    if ($this->input->post()) {
      // введены данные формы
      if (Auth::instance()->login($_POST['username'], $_POST['password'])) {
        $this->user = Auth::instance()->get_user();     
        url::redirect(url::base(FALSE).'site_auth/profile');
      }
      else $errors['login'] = 'login failed!';
    }
    $this->template->content->errors = $errors;
  }
  public function index() {
    $this->user ? url::redirect(url::base(FALSE).'site_auth/profile') : url::redirect(url::base(FALSE).'site_auth/login');
  }

  public function profile() {
    if (!$this->user = Auth::instance()->get_user())
      url::redirect(url::base(FALSE).'site_auth/login');
    $this->template->title = 'Информация о пользователе';
    $this->template->content = new View('auth/profile');
    $this->template->content->errors = array();

    $userdata = ORM::factory('user_detail', $this->user->id);
    $this->template->content->userdata = arr::merge($this->user->as_array(), $userdata->as_array());
    }

    public function logout() {
      $this->user OR url::redirect(url::base(FALSE).'site_auth/login');
      if (Auth::instance()->logout()) {
        $this->user = FALSE;
        url::redirect(url::base(FALSE).'site_auth/login');
      }
    }
}
